// 用户状态管理 - Pinia Store
import { defineStore } from 'pinia'
import type { User } from '@/types'
import { ref } from 'vue'
import { login } from '@/api/user'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref<string>('')
  const user = ref<User | null>(null)
  const isAuthenticated = ref(false)

  // 登录动作
  const loginReq = async (username: string, password: string) => {
    try {
      const { token: responseToken, user: userInfo } = await login({username, password})

      // 更新状态
      token.value = responseToken
      user.value = userInfo
      isAuthenticated.value = true

      // 持久化存储
      localStorage.setItem('token', responseToken)
      localStorage.setItem('user', JSON.stringify(userInfo))

      return userInfo
    } catch (error) {
      logout()
      throw error
    }
  }

  // 登出动作
  const logout = () => {
    token.value = ''
    user.value = null
    isAuthenticated.value = false
    localStorage.removeItem('token')
    localStorage.removeItem('user')
  }

  // 初始化时从本地存储恢复状态
  const initFromStorage = () => {
    const storedToken = localStorage.getItem('token')
    const storedUser = localStorage.getItem('user')

    if (storedToken && storedUser) {
      token.value = storedToken
      user.value = JSON.parse(storedUser)
      isAuthenticated.value = true
    }
  }

  // 立即执行初始化
  initFromStorage()

  return {
    token,
    user,
    isAuthenticated,
    loginReq,
    logout,
    initFromStorage
  }
})